package com.veryUsedCar.controller;
import cn.hutool.json.JSONUtil;
import com.veryUsedCar.data.Result;
import com.veryUsedCar.dto.UserDTO;
import com.veryUsedCar.enums.ConstantEnum;
import com.veryUsedCar.utils.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@RequestMapping("/login/v1")
public class LoginController {

    @Autowired
    private JwtUtil jwtUtil;
    //denglu
    @PostMapping
    public Result login(@RequestBody UserDTO user){
        //
        Subject subject = SecurityUtils.getSubject();
        //封装token
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUname(), user.getPassword());
        try {
            subject.login(token);
            List<Result> list = subject.getPrincipals().asList();
            UserDTO data = (UserDTO) list.get(0).getData();
           String admin = jwtUtil.createJwt(String.valueOf(data.getUid()), JSONUtil.toJsonStr(data),"admin");
            return Result.build(ConstantEnum.SUCCESS).setData(admin);
        } catch (UnknownAccountException e) {
            return Result.build(ConstantEnum.ERROR);
        }catch (IncorrectCredentialsException e2){
            return Result.build(ConstantEnum.DPASSWORD_ERROR);
        }
    }
}
